<?php

namespace App\Models\Factory;

use App\Helpers\Http\HttpClient;
use App\Helpers\Utils;
use App\Models\AbsModelFactory;
use App\Models\Orm\SmsConfig;
use App\Models\Orm\SystemConfig;
use App\Strategies\SmsStrategy;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;

/**
 * 短信工厂
 * Class SmsFactory
 * @package App\Models\Factory
 */
class SmsFactory extends AbsModelFactory
{

//    /**
//     * 请求创蓝发送短信
//     */
//    //创蓝发送短信接口URL, 如无必要，该参数可不用修改
    const API_SEND_URL = 'http://sms.253.com/msg/send';
//
//    //创蓝短信余额查询接口URL, 如无必要，该参数可不用修改
//    const API_BALANCE_QUERY_URL = 'http://sms.253.com/msg/balance';
//
    const API_ACCOUNT = 'N13811875123';//创蓝账号 替换成你自己的账号

    const API_PASSWORD = '612941';//创蓝密码 替换成你自己的密码

    /**
     * 把短信验证码存储在cache中（过期时间为60s）
     * @param $key
     * @param $value
     * @return bool
     */
    public static function putSmsCodeToCache($key, $value, $sec = 300)
    {
        Cache::put($key, $value, Carbon::now()->second($sec));
        return true;
    }


    /**
     * 从cache中获取存储的短信验证码
     * @param $key
     */
    public static function getSmsCodeFromCache($key)
    {
        return Cache::get($key);
    }


    /**
     * 把发送短信验证码时生成的32二位随机数存储进cache
     * @param $key
     * @param $value
     * @return bool
     */
    public static function putSmsRandomToCache($key, $value, $sec = 100)
    {
        Cache::put($key, $value, Carbon::now()->second($sec));
        return true;
    }


    /**
     * 从cache中取出发送短信验证码时存进的随机数
     * @param $key
     * @return mixed
     */
    public static function getSmsRandomFromCache($key)
    {
        return Cache::get($key);
    }

    /**
     * @param $mobile
     * 验证短信1分钟之内不能重复发送
     */
    public static function checkCodeExistenceTime($mobile)
    {
        $codeKey = $mobile . '_send_limit';
        if (CacheFactory::existValueFromCache($codeKey)) {
            return false;
        }
        return true;
    }

    /**
     * 根据nid查找系统配置中的短信通道的value
     * @param $nid
     */
    public static function getSmsSystemConfig()
    {
        $system_config = SystemConfig::select('value')->where('nid', '=', 'sms_config')->where('status', '=', '1')->first();
        return $system_config->value;
    }


    /**
     * 发送短信
     *
     * @param string $mobile 手机号码
     * @param string $msg 短信内容
     * @param string $needstatus 是否需要状态报告
     */
    public static function sendCode($mobile)
    {
        $code = rand(1000, 9999);
        $msg = "【现金贷】（安稳贷）您好，您的验证码是" . $code;
        $needstatus = 1;
        if (preg_match('/^0?(13|14|15|17|18)[0-9]{9}$/', $mobile)) {
            // 将该验证码和手机号发送给第三方，第三方通过短信的方式向用户发送信息
            //创蓝接口参数
            $postArr = array(
                'un' => self::API_ACCOUNT,
                'pw' => self::API_PASSWORD,
                'msg' => $msg,
                'phone' => $mobile,
                'rd' => $needstatus,
            );
            self::curlPost(self::API_SEND_URL, $postArr);

            CacheFactory::putValueToCache($mobile . '_code', $code, 5 * 60);
            CacheFactory::putValueToCache($mobile . '_send_limit', $mobile, 60);

            return json_encode(array('isSuccess' => "1", 'status' => "1", "msg" => "短信验证码发送成功", "check" => $code));
        } else {
            return json_encode(array('isSuccess' => "0", 'status' => "0", "error" => "44000227", "msg" => "短信验证码发送失败"));
            // 手机号格式不正确
        }

    }

//短信邀请好友
    public static function sendInviteCode($mobile, $code, $userphone)
    {

        $msg = "您好，您的好友" . $userphone . "邀请您注册安稳钱包" . "http://test.m.anwenqianbao.com/#/login?inviteCode=" . $code;
        $needstatus = 1;
        if (preg_match('/^0?(13|14|15|17|18)[0-9]{9}$/', $mobile)) {
            // 将该验证码和手机号发送给第三方，第三方通过短信的方式向用户发送信息
            //创蓝接口参数
            $postArr = array(
                'un' => self::API_ACCOUNT,
                'pw' => self::API_PASSWORD,
                'msg' => $msg,
                'phone' => $mobile,
                'rd' => $needstatus,
            );
            self::curlPost(self::API_SEND_URL, $postArr);

            CacheFactory::putValueToCache($mobile . '_send_limit', $mobile, 60);

            return true;
        } else {
            return false;
        }

    }



    private static function curlPost($url, $postFields)
    {
        $postFields = http_build_query($postFields);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }


    /**
     * 限制ip请求次数
     * 次数限制有效期为1天
     * @return mixed
     */
    public static function limitIp()
    {
        $ip = Utils::ipAddress();
        $key = 'anwen_ip_value_' . $ip;
        if (Cache::has($key)) {
            Cache::increment($key, 1);
        } else {
            Cache::put($key, 1, Carbon::now()->second(60 * 60 * 24));
        }
        return Cache::get($key);
    }


    /**
     * 手机号次数限制
     * 次数限制有效期为1天
     * @param $mobile
     * @return mixed
     */
    public static function limitMobile($mobile)
    {
        $key = 'anwen_mobile_value_' . $mobile;
        if (Cache::has($key)) {
            Cache::increment($key, 1);
        } else {
            Cache::put($key, 1, Carbon::now()->second(60 * 60 * 24));
        }
        return Cache::get($key);

    }


    /**
     * 获取短信配置中value
     * @return string
     */
    public static function  getSmsConfig()
    {
        $config = SmsConfig::where('status',1)->first();
        return $config ? $config->value : '';
    }

}
